﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace iTunesApp
{
    public partial class FormMain : Form
    {
        private Database _data = new Database();
        private int _stt;
        private IList<Request> _list;
        private IList<Request> _listAdd;
        private IList<Request> _listUpdate;
        private IList<int> _listDelete;
        public FormMain()
        {
            InitializeComponent();
            _list = new List<Request>();
            _listAdd = new List<Request>();
            _listUpdate = new List<Request>();
            _listDelete = new List<int>();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            var addSuccess = _listAdd.Count(req => _data.Insert(req));
            var updateSuccess = _listUpdate.Count(req => _data.Update(req));
            var deleteSuccess = _listDelete.Count(id => _data.Delete(id));

            var msg = string.Format("Add success: {0}\nUpdate success: {1}\nDelete success: {2}", addSuccess, updateSuccess, deleteSuccess);
            Utilites.ShowMessage(msg);

            btnSubmit.Enabled = false;
        }

        private delegate void LoadAsync();
        private void FormMain_Load(object sender, EventArgs e)
        {
            _list = _data.GetAll().ToList();
            if (_list == null) return;
            _list = _list.OrderBy(req => req.Artist).ToList();
            // delegate for free main thread
            BeginInvoke(new LoadAsync(LoadListViewAsync));
            //LoadListView();

            btnSubmit.Enabled = false;

        }

        private void LoadListViewAsync()
        {
            LoadListView();
        }
        private void LoadListView(IEnumerable<Request> list = null)
        {
            _stt = 1;
            if (list == null)
            {
                list = _list;
            }
            lstView.Items.Clear();
            foreach (var req in list)
            {
                AddItemToListView(req);
            }
        }

        private void AddItemToListView(Request req)
        {
            var item = new ListViewItem("" + _stt++) { Tag = req.Id };
            item.SubItems.Add(req.Artist);
            item.SubItems.Add(req.AlbumSingle);
            item.SubItems.Add(req.BackupAccount);
            item.SubItems.Add(req.FBAccount);
            item.SubItems.Add(req.Url);
            lstView.Items.Add(item);
        }

        private bool sortArtist;
        private bool sortAlbum;
        private bool sortBackup;
        private bool sortFB;
        private void lstView_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            switch (e.Column)
            {
                case 1:
                    // sort by artist
                    if (!sortArtist)
                    {
                        _list = _list.OrderBy(req => req.Artist).ToList();
                        sortArtist = true;
                    }
                    else
                    {
                        _list = _list.OrderByDescending(req => req.Artist).ToList();
                        sortArtist = false;
                    }
                    break;
                case 2:
                    // sort by album/single
                    if (!sortAlbum)
                    {
                        _list = _list.OrderBy(req => req.AlbumSingle).ToList();
                        sortAlbum = true;
                    }
                    else
                    {
                        _list = _list.OrderByDescending(req => req.AlbumSingle).ToList();
                        sortAlbum = false;
                    }
                    break;
                case 3:
                    // sort by backup account
                    if (!sortBackup)
                    {
                        _list = _list.OrderBy(req => req.BackupAccount).ToList();
                        sortBackup = true;
                    }
                    else
                    {
                        _list = _list.OrderByDescending(req => req.BackupAccount).ToList();
                        sortBackup = false;
                    }
                    break;
                case 4:
                    // sort by fb album
                    if (!sortFB)
                    {
                        _list = _list.OrderBy(req => req.FBAccount).ToList();
                        sortFB = true;
                    }
                    else
                    {
                        _list = _list.OrderByDescending(req => req.FBAccount).ToList();
                        sortFB = false;
                    }
                    break;
            }
            LoadListView();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                _listAdd.Clear();
                _listUpdate.Clear();
                _listDelete.Clear();
                _list = _data.GetAll().OrderBy(req => req.Artist).ToList();
                BeginInvoke(new LoadAsync(LoadListViewAsync));
            }
            catch (Exception exception)
            {
                Debug.WriteLine("Refresh: " + exception.Message);
            }
            finally
            {
                btnSubmit.Enabled = false;
            }



            //LoadListView();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (saveFile.ShowDialog() != DialogResult.OK) return;
            var filename = saveFile.FileName;
            try
            {
                if (File.Exists(filename))
                    File.Delete(filename);
                Utilites.ExportToExcel(filename, _list);
                MessageBox.Show("Export success");
            }
            catch (Exception exception)
            {
                MessageBox.Show("Export failure\nError: " + exception.Message);
                Debug.WriteLine("Export excel: " + exception.Message);
            }

        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!CheckedControl())
            {
                Utilites.ShowMessageError("Textbox is empty or/and Url is invalid\nPlease check and try again!!!");
                return;
            }
            var req = CreateRequest();

            _listAdd.Add(req);
            _list.Add(req);

            AddItemToListView(req);

            btnReset_Click(sender, e);
            btnSubmit.Enabled = true;
        }

        private bool CheckedControl()
        {
            if (txtArtitsName.Text.Trim().Length < 1 ||
                txtAlbumSingle.Text.Trim().Length < 1 ||
                txtBackupAccount.Text.Trim().Length < 1 ||
                txtFBAlbum.Text.Trim().Length < 1)
            {
                return false;
            }

            return txtUrl.Text.Trim().isValidUrl();
        }

        private void lstView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstView.SelectedItems.Count < 1) return;
            var index = lstView.SelectedItems[0].Index;
            var req = _list[index];

            SetValueTextbox(req);
        }

        private void SetValueTextbox(Request req = null)
        {
            if (req == null)
                req = new Request();
            btnUpdate.Tag = req.Id;
            txtArtitsName.Text = req.Artist;
            txtAlbumSingle.Text = req.AlbumSingle;
            txtBackupAccount.Text = req.BackupAccount;
            txtFBAlbum.Text = req.FBAccount;
            txtUrl.Text = req.Url;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lstView.SelectedItems.Count < 1)
            {
                Utilites.ShowMessageError("No Rows selected");
                return;
            }
            if (Utilites.ShowQuestionMessage("Do you want to delete?") == DialogResult.No) return;

            foreach (var item in lstView.SelectedItems.Cast<ListViewItem>())
            {
                var reqId = (int)item.Tag;
                if (reqId < 1)
                {
                    var list = _listAdd.ToList();
                    foreach (var ite in list.Where(i => i.Id == 0))
                    {
                        _listAdd.Remove(ite);
                    }
                }
                else
                {
                    _listDelete.Add(reqId);
                }

                lstView.Items.Remove(item);
            }

            btnReset_Click(sender, e);
            btnSubmit.Enabled = true;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (lstView.SelectedItems.Count < 1)
            {
                Utilites.ShowMessageError("No Rows selected");
                return;
            }

            var reqId = (int)btnUpdate.Tag;
            if (reqId < 1) return;
            if (!CheckedControl())
            {
                Utilites.ShowMessageError("Textbox is empty or/and Url is invalid\nPlease check and try again!!!");
                return;
            }
            var req = CreateRequest(reqId);

            _listUpdate.Add(req);
            lstView.SelectedItems[0].SubItems[1].Text = req.Artist;
            lstView.SelectedItems[0].SubItems[2].Text = req.AlbumSingle;
            lstView.SelectedItems[0].SubItems[3].Text = req.BackupAccount;
            lstView.SelectedItems[0].SubItems[4].Text = req.FBAccount;
            lstView.SelectedItems[0].SubItems[5].Text = req.Url;

            btnReset_Click(sender, e);
            btnSubmit.Enabled = true;
        }



        private Request CreateRequest(int id = 0)
        {
            var req = new Request
                          {
                              Id = id,
                              Artist = txtArtitsName.Text.Replace("\'", string.Empty),
                              AlbumSingle = txtAlbumSingle.Text.Replace("\'", string.Empty),
                              BackupAccount = txtBackupAccount.Text.Replace("\'", string.Empty),
                              FBAccount = txtFBAlbum.Text.Replace("\'", string.Empty),
                              Url = txtUrl.Text.Replace("\'", string.Empty)
                          };

            return req;
        }
        private void btnReset_Click(object sender, EventArgs e)
        {
            lstView.SelectedItems.Clear();
            SetValueTextbox();
            btnSubmit.Enabled = false;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() != DialogResult.OK) return;
            try
            {
                var list = Utilites.ImportFromExcel(openFile.FileName);
                if (list == null)
                {
                    Utilites.ShowMessageError("Can not import\nPlease recheck file source and try again");
                    return;
                }

                foreach (var req in list)
                {
                    _list.Add(req);
                    _listAdd.Add(req);
                    AddItemToListView(req);
                }
            }
            catch (Exception exception)
            {
                Utilites.ShowMessageError("Error: " + exception.Message);
                Debug.WriteLine("Error: " + exception.Message);
            }


            btnSubmit.Enabled = true;
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnDelete_Click(sender, e);
        }

        private void reloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnRefresh_Click(sender, e);
        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnImport_Click(sender, e);
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnExport_Click(sender, e);
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in lstView.Items.Cast<ListViewItem>())
            {
                item.Selected = true;
            }
        }

        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectAllToolStripMenuItem_Click(sender, e);
            btnDelete_Click(sender, e);
        }

    }
}
